package spi.mySpi;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import spi.Hello;

import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;

public class mySpi{

    private static final String pre_fix="src/";
    private static final String back_fix="SpiConfig.properties";
    private static final Logger logger=LoggerFactory.getLogger(mySpi.class);

    public static Hello getInstance(String inter, String type) throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException {
            String pos=pre_fix+inter+back_fix;
            logger.info(pos);
        Properties properties=new Properties();
        properties.load(new FileInputStream(pos));
        String class_pos = properties.getProperty(type);
        if (class_pos==null){
            logger.error("no such class");
            return null;
        }
        ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
        Class<?> aClass = contextClassLoader.loadClass(class_pos);
        if (aClass==null){
            logger.error("load class error");
            return null;
        }
        // TODO 判断是否有spi接口
        Object o = aClass.newInstance();

        //依赖注入，解析set方法
        Method[] methods = aClass.getMethods();
        for (Method method:methods){
            if (method.getName().startsWith("set")){
                Class<?>[] parameterTypes = method.getParameterTypes();
                for (Class clz:parameterTypes){
                    if (!clz.isInterface()){
                        //todo 处理java普通类
                        if (clz==String.class){
                            String s="init!";
                            method.invoke(o,s);
                        }

                    }else {
                        // todo 处理是接口的情况，一般对应于其它spi接口
                    }
                }
            }
        }
        //todo aop
        return (Hello)o;
    }

}
